import {
  Component,
  Input,
  Output,
  HostBinding,
  ElementRef,
  EventEmitter,
  Host,
  AfterContentInit,
  OnDestroy,
} from '@angular/core';

import { TableComponent } from './table.component';
import { TableFlexService } from './table-flex.service';
import { TableScrollService } from './table-scroll.service';
import { TableSortService, SortState, SortMode } from './table-sort.service';
import { TableSelectService } from './table-select.service';
import { TableSelectBase } from './table-select-base';

@Component({
  selector: 'fui-table-head',
  templateUrl: './table-head.component.html',
  providers: [
    TableSortService,
  ],
})
export class TableHeadComponent extends TableSelectBase implements AfterContentInit, OnDestroy {
  @HostBinding('class.fui-table-head') hostClass = true;

  /**
   * Specify the attribute attached to a selected datum.
   * Default value is '_selected' if not set.
   */
  @Input() set selectedKey(key: string) {
    this.tableSelect.selectedKey = key;
  }

  /**
   * Sort mode, support 'single', 'multiple'.
   * Default value is 'single'.
   */
  @Input() set sortMode(mode: SortMode) {
    this.tableSort.setMode(mode);
  }

  /** Emit sort state changes. */
  @Output() sortChange = new EventEmitter<SortState>();

  get selected() {
    return this.tableSelect.isAllSelected();
  }

  constructor(
    public element: ElementRef,
    @Host() public table: TableComponent,
    public tableFlex: TableFlexService,
    public tableScroll: TableScrollService,
    public tableSort: TableSortService,
    public tableSelect: TableSelectService,
  ) {
    super();
    this.tableScroll.scrollSubject.subscribe(({enabled, scrollbarWidth}) => {
      if (enabled) {
        this.element.nativeElement.style['padding-right'] = `${scrollbarWidth}px`;
      }
    });
    this.tableSort.sortChangeSubject.subscribe((changes) => {
      this.sortChange.emit(changes);
    });
  }

  ngAfterContentInit() {
    this.tableFlex.register(this.element.nativeElement);
  }

  ngOnDestroy() {
    this.tableFlex.unregister(this.element.nativeElement);
    this.tableScroll.scrollSubject.unsubscribe();
  }

  updateData(selected) {
    this.tableSelect.batchSelect(selected);
  }

}
